<template>
  <div class="system-config">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="系统配置" name="system">
        <el-card>
          <template #header>
            <span>系统配置</span>
          </template>
          <el-form :model="systemConfig" label-width="120px">
            <el-form-item label="系统名称">
              <el-input v-model="systemConfig.name" />
            </el-form-item>
            <el-form-item label="系统描述">
              <el-input v-model="systemConfig.description" type="textarea" />
            </el-form-item>
            <el-form-item label="配置键">
              <el-input v-model="systemConfig.key" disabled />
            </el-form-item>
            <el-form-item label="配置值">
              <el-input v-model="systemConfig.value" type="textarea" :rows="4" />
            </el-form-item>
            <el-form-item label="Logo">
              <el-upload
                class="avatar-uploader"
                :auto-upload="true"
                :show-file-list="false"
                :on-success="handleLogoSuccess"
                :before-upload="beforeLogoUpload"
                :http-request="customUpload"
                action="#"
              >
                <img v-if="systemConfig.logo" :src="systemConfig.logo" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="状态">
              <el-switch v-model="systemConfig.status" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveSystemConfig">保存配置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="配置管理" name="config">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>配置管理</span>
              <el-button type="primary" @click="handleAddConfig">
                <el-icon>
                  <Plus />
                </el-icon>新增配置
              </el-button>
            </div>
          </template>

          <el-table :data="configList" v-loading="loading" border>
            <el-table-column prop="key" label="配置键" />
            <el-table-column prop="value" label="配置值" show-overflow-tooltip />
            <el-table-column prop="name" label="配置名称" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="type" label="类型" width="80">
              <template #default="{ row }">
                <el-tag size="small">{{ row.type || 'string' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <DictTag dict-type="sys_status" :value="row.status" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEditConfig(row)">
                  <el-icon>
                    <Edit />
                  </el-icon>编辑
                </el-button>
                <el-button type="danger" size="small" @click="handleDeleteConfig(row)">
                  <el-icon>
                    <Delete />
                  </el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 配置表单对话框 -->
    <ConfigFormDialog
      v-model="dialogVisible"
      :config-data="currentConfig"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getSystemConfig,
  createConfig,
  updateConfig,
  getConfigList,
  deleteConfig,
} from "@/api/config";
import { uploadImage } from "@/api/image";
import ConfigFormDialog from "@/components/ConfigFormDialog.vue";
import DictTag from "@/components/DictTag.vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";

const activeTab = ref("system");
const systemConfig = reactive({
  id: null,
  key: "system_config",
  name: "",
  value: "",
  logo: "",
  description: "",
  status: true,
  type: "json",
});

// 注入刷新系统名称的方法
const refreshSystemName = inject("refreshSystemName", () => {});

const loading = ref(false);
const configList = ref([]);
const dialogVisible = ref(false);
const currentConfig = ref(null);

const loadSystemConfig = async () => {
  try {
    const data = await getSystemConfig({ key: "system_config" });
    if (data) {
      // 解析JSON格式的配置值
      try {
        const configData = JSON.parse(data.value || "{}");
        Object.assign(systemConfig, {
          id: data.id,
          key: data.key,
          name: data.name,
          value: data.value,
          logo: configData.logo || "",
          description: data.description,
          status: data.status,
          type: data.type,
        });
        // 设置系统名称和描述
        if (configData.systemName) systemConfig.name = configData.systemName;
        if (configData.systemDescription)
          systemConfig.description = configData.systemDescription;
      } catch (e) {
        // 如果不是JSON格式，直接使用
        Object.assign(systemConfig, data);
      }
    }
  } catch (error) {
    ElMessage.error("获取系统配置失败");
  }
};

const loadConfigList = async () => {
  loading.value = true;
  try {
    const data = await getConfigList();
    // 过滤掉系统配置，避免重复显示
    configList.value = (data.list || []).filter(
      (item) => item.key !== "system_config"
    );
  } catch (error) {
    ElMessage.error("获取配置列表失败");
  } finally {
    loading.value = false;
  }
};

const saveSystemConfig = async () => {
  try {
    const configData = {
      key: "system_config",
      name: systemConfig.name,
      value: JSON.stringify({
        systemName: systemConfig.name,
        systemDescription: systemConfig.description,
        logo: systemConfig.logo,
      }),
      description: systemConfig.description,
      status: systemConfig.status,
      type: "json",
    };

    if (systemConfig.id) {
      await updateConfig(systemConfig.id, configData);
    } else {
      await createConfig(configData);
    }
    ElMessage.success("保存成功");
    // 刷新系统名称
    refreshSystemName();
  } catch (error) {
    ElMessage.error("保存失败");
  }
};

const handleAddConfig = () => {
  currentConfig.value = null;
  dialogVisible.value = true;
};

const handleEditConfig = (row) => {
  currentConfig.value = { ...row };
  dialogVisible.value = true;
};

const handleDeleteConfig = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该配置吗？", "提示");
    await deleteConfig(row.id);
    ElMessage.success("删除成功");
    loadConfigList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const handleSuccess = () => {
  dialogVisible.value = false;
  loadConfigList();
};

const handleLogoSuccess = (response, file) => {
  // 自定义上传成功后的回调
  // Logo上传成功处理
};

// 自定义上传方法
const customUpload = ({ file }) => {
  // 使用图片管理的上传接口
  return uploadLogoImage(file);
};

const beforeLogoUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return (isJPG || isPNG) && isLt2M;
};

// 使用图片管理接口上传logo
const uploadLogoImage = async (file) => {
  try {
    const formData = new FormData();
    formData.append("file", file);

    const response = await uploadImage(formData);

    // 假设返回的response包含url字段，或者根据实际API返回结构调整
    const logoUrl = response.url || response[0]?.url;

    // 更新系统配置中的logo URL
    systemConfig.logo = logoUrl;

    ElMessage.success("Logo上传成功");
    return { success: true, url: logoUrl };
  } catch (error) {
    // ElMessage.error("Logo上传失败: " + (error.message || "未知错误"));
    return { success: false, error: error };
  }
};

onMounted(() => {
  loadSystemConfig();
  loadConfigList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>